<script setup>
import ChatBox from '@/components/chat/ChatBox.vue'
import { inject, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useChannelStore } from '@/stores/channels'
import { useChatStore } from '@/stores/chat'
import { useConfigStore } from '@/stores/config'
import { useAuthStore } from '@/stores/auth'
import { getStorageUrl, setDocumentText } from '@/utils/utils'

const route = useRoute()
const isSmallPage = inject('isSmallPage')

const channelStore = useChannelStore()
const chatStore = useChatStore()
const configStore = useConfigStore()
const authStore = useAuthStore()

const sessionId = computed(() => parseInt(route.params?.id || 0))

const session = inject('session')
const drawerRef = inject('drawerRef')

const role = computed(() => {
  return {
    user: { avatar: authStore.getAvatar() },
    assistant: { avatar: getStorageUrl(configStore.get('chat.avatar')) },
  }
})

watch(
  () => route.params.id,
  () => {
    if (isSmallPage.value) {
      drawerRef.value?.close()
    }
  },
  { immediate: true }
)

watch(
  () => chatStore.active,
  (val) => {
    if (val) setDocumentText(val.name)
  },
  { immediate: true }
)

onMounted(async () => {
  await channelStore.init()
})
</script>

<template>
  <ChatBox
    show-delete-btn
    show-rename-btn
    show-style-btn
    show-context-btn
    :default-display-style="chatStore.displayStyle()"
    object-type="unlimited"
    :object-id="sessionId"
    :channels="channelStore.data"
    :channel="channelStore.active"
    :role="role"
    :chat-info="{ title: chatStore.active?.name }"
    :welcome-text="configStore.get('chat.welcome_text')"
    :example-text="configStore.get('chat.example_questions')"
    :prompt-placeholder="configStore.get('chat.prompt_placeholder')"
    @rename-chat="session.rename(sessionId)"
    @delete-chat="session.remove(sessionId)"
    @switch-channel="channelStore.switch"
    @switch-style="chatStore.displayStyle"
  >
  </ChatBox>
</template>
